package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.CarInsurance;
import com.kuanter.kuanterauto.entity.VehicleInfo;
import com.kuanter.kuanterauto.entity.VehicleInfoList;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.DimensUtil;
import com.kuanter.kuanterauto.utils.JsonParser;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.kuanter.kuanterauto.view.SelectPicPopupWindow;
import com.umeng.analytics.MobclickAgent;

public class InsuranceActivity extends BaseActivity_NoBar {
	RelativeLayout insurance_top;
	LayoutInflater factory;
	TextView add_insurance;
	LinearLayout liner_cx;
	
	List<CarInsurance> list_insu;
	
	int click_num = 0;
	
	ProApplication application;
	List<VehicleInfo> vehicleInfo;
	
	SelectPicPopupWindow menuWindow; //弹出的选择器
	
	OnItemClickListener itemsOnClick = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			final CarInsurance car = list_insu.get(position);
			View show_view = liner_cx.getChildAt(click_num);
			RelativeLayout rl_xzqc = (RelativeLayout) show_view.findViewById(R.id.rl_xzqc);
			int dp_height = 40;
			if(screenWidth == 480) {
				dp_height = 40;
			} else if(screenWidth == 720 || screenWidth == 800) {
				dp_height = 48;
			} else if(screenWidth == 540) {
				dp_height = 46;
			}
			LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, DimensUtil.dipTopx(InsuranceActivity.this, dp_height));
			lp.bottomMargin = 0;
			
			rl_xzqc.setBackgroundResource(R.drawable.setting_item_top_corner);
			rl_xzqc.setLayoutParams(lp);
			
			RelativeLayout row_2 = (RelativeLayout) show_view.findViewById(R.id.row_2);
			ImageView cximg = (ImageView) show_view.findViewById(R.id.cximg);
			
			TextView cxID = (TextView) show_view.findViewById(R.id.bxID);
			TextView cxname = (TextView) show_view.findViewById(R.id.cxname);
			TextView cxad = (TextView) show_view.findViewById(R.id.cxad);
			TextView bxdh = (TextView) show_view.findViewById(R.id.bxdh);
			TextView xbdh = (TextView) show_view.findViewById(R.id.xbdh);
			TextView bd = (TextView) show_view.findViewById(R.id.weatherBD);
			bd.setVisibility(View.GONE);
			
			MerchantTurnActivity1.DownLoadImage dli = new MerchantTurnActivity1.DownLoadImage(150, 150, cximg);
			dli.execute(car.getInsuranceImgUrl());
			
			row_2.setVisibility(View.VISIBLE);
			cximg.setVisibility(View.VISIBLE);
			cxname.setVisibility(View.VISIBLE);
			cxad.setVisibility(View.VISIBLE);
			bxdh.setVisibility(View.VISIBLE);
			xbdh.setVisibility(View.VISIBLE);
			
			cxID.setText(car.getInsuranceID());
			
			cxname.setText(car.getInsuranceName());
			cxad.setText(car.getInsuranceAd());
		/*	if(car.getPhoneName1().equals("保险电话")) {
				bxdh.setText(car.getPhoneName1() + ": " + car.getInsuranceTel());
			} else if(car.getPhoneName2().equals("保险电话")) {
				bxdh.setText(car.getPhoneName2() +":" + car.getRenewalTel());
			} else if(car.getPhoneName3().equals("保险电话")) {
				bxdh.setText(car.getPhoneName3() + ":" + car.getPhonenum3());
			} else if(car.getPhoneName4().equals("保险电话")) {
				bxdh.setText(car.getPhoneName4() + ":" + car.getPhonenum4());
			} else {
				bxdh.setText("保险电话:暂无");
			}*/
			bxdh.setText("保险电话:" + car.getBxdh());
			
			/*if(car.getPhoneName1().equals("续保电话")) {
				xbdh.setText(car.getPhoneName1() + ": " + car.getInsuranceTel());
			} else if(car.getPhoneName2().equals("续保电话")) {
				xbdh.setText(car.getPhoneName2() +":" + car.getRenewalTel());
			} else if(car.getPhoneName3().equals("续保电话")) {
				xbdh.setText(car.getPhoneName3() + ":" + car.getPhonenum3());
			} else if(car.getPhoneName4().equals("续保电话")) {
				xbdh.setText(car.getPhoneName4() + ":" + car.getPhonenum4());
			} else {
				xbdh.setText("保险电话:暂无");
			}*/
			xbdh.setText("续保电话:" + car.getXbdh());
			
			bxdh.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent_call_bx = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + car.getInsuranceTel()));
					startActivity(intent_call_bx);
				}
			});
			
			xbdh.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent_call_xb = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + car.getRenewalTel()));
					startActivity(intent_call_xb);
				}
			});
			
			if(menuWindow != null) {
				menuWindow.dismiss();
			}
		}
	};
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				Log.i("bbb", json);
				list_insu = JsonParser.getInsurance(json);
				
				if(application.getList_vehicleInfo() != null && application.getList_vehicleInfo().size() > 0) {
					vehicleInfo = application.getList_vehicleInfo();
					addInView();
					finishProgress();
				} else {
					DataLoader loader_car = new DataLoader(InsuranceActivity.this);
					String url_car = MainConstants.HOST_test + HttpConfigAPI.FINDVEHICLE;
					List<NameValuePair> list_car = new ArrayList<NameValuePair>();
					NameValuePair params_car = new BasicNameValuePair("vehicleInfo.userId", SharePrefenceUtil.getUserID(InsuranceActivity.this) + "");
					list_car.add(params_car);
					loader_car.DisplayData(url_car, list_car, mHandler_car, "", false);
				}
				
			} else {
				showToast("网络错误");
				finishProgress();
			}
			super.handleMessage(msg);
		}
		
	};
	
	public void addInView() {
		if(vehicleInfo != null) {
			for(int i = 0; i < vehicleInfo.size(); i++) {
				final int j = i;
				VehicleInfo info = vehicleInfo.get(i);
				View cx = factory.inflate(R.layout.insurance_item, null);
				
				//设置值
				TextView car_num = (TextView) cx.findViewById(R.id.car_num);
				TextView bxID = (TextView) cx.findViewById(R.id.bxID);
				if(car_num != null) {
					if(info != null) {
						if(info.getLicensePlateNumber() != null) {
							car_num.setText(info.getLicensePlateNumber());
							bxID.setText(info.getInsuranceCompanyId());
						}
					}
				}
				
				RelativeLayout rl_xzqc = (RelativeLayout) cx.findViewById(R.id.rl_xzqc);
				rl_xzqc.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						click_num = j;
//						Toast.makeText(InsuranceActivity.this, "弹出选择器", Toast.LENGTH_SHORT).show();
						menuWindow = new SelectPicPopupWindow(InsuranceActivity.this, itemsOnClick,list_insu);
		                menuWindow.showAtLocation(InsuranceActivity.this.findViewById(R.id.pushAn_main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
					}
				});
				
//				RelativeLayout row_2 = (RelativeLayout) cx.findViewById(R.id.row_2);
				ImageView cximg = (ImageView) cx.findViewById(R.id.cximg);
				TextView cxname = (TextView) cx.findViewById(R.id.cxname);
				TextView cxad = (TextView) cx.findViewById(R.id.cxad);
				TextView bxdh = (TextView) cx.findViewById(R.id.bxdh);
				TextView xbdh = (TextView) cx.findViewById(R.id.xbdh);
				TextView bd = (TextView) cx.findViewById(R.id.weatherBD);
				bd.setVisibility(View.VISIBLE);
				RelativeLayout row_2 = (RelativeLayout) cx.findViewById(R.id.row_2);
				
				for(int n = 0; n < list_insu.size(); n++) {
					final CarInsurance car = list_insu.get(n);
					if(car.getInsuranceID().equals(info.getInsuranceCompanyId())) {  //"1"
						MerchantTurnActivity1.DownLoadImage dli = new MerchantTurnActivity1.DownLoadImage(150, 150, cximg);
						dli.execute(car.getInsuranceImgUrl());
						
						cxname.setText(car.getInsuranceName());
						cxad.setText(car.getInsuranceAd());
						
						/*if(car.getPhoneName1().equals("保险电话")) {
							bxdh.setText(car.getPhoneName1() + ": " + car.getInsuranceTel());
						} else if(car.getPhoneName2().equals("保险电话")) {
							bxdh.setText(car.getPhoneName2() +":" + car.getRenewalTel());
						} else if(car.getPhoneName3().equals("保险电话")) {
							bxdh.setText(car.getPhoneName3() + ":" + car.getPhonenum3());
						} else if(car.getPhoneName4().equals("保险电话")) {
							bxdh.setText(car.getPhoneName4() + ":" + car.getPhonenum4());
						} else {
							bxdh.setText("保险电话:暂无");
						}
						*/
						bxdh.setText("保险电话:" + car.getBxdh());
						
						/*if(car.getPhoneName1().equals("续保电话")) {
							xbdh.setText(car.getPhoneName1() + ": " + car.getInsuranceTel());
						} else if(car.getPhoneName2().equals("续保电话")) {
							xbdh.setText(car.getPhoneName2() +":" + car.getRenewalTel());
						} else if(car.getPhoneName3().equals("续保电话")) {
							xbdh.setText(car.getPhoneName3() + ":" + car.getPhonenum3());
						} else if(car.getPhoneName4().equals("续保电话")) {
							xbdh.setText(car.getPhoneName4() + ":" + car.getPhonenum4());
						} else {
							xbdh.setText("续保电话:暂无");
						}*/
						xbdh.setText("续保电话:" + car.getXbdh());
						
//						bxdh.setText(car.getPhoneName1() + ": " + car.getInsuranceTel());
//						xbdh.setText(car.getPhoneName2() + ":" + car.getRenewalTel());
						
						bxdh.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								if(!car.getBxdh().equals("暂无")) {
									new AlertDialog.Builder(InsuranceActivity.this)
									.setMessage("是否拨打电话：" + car.getBxdh())
									.setPositiveButton("确认", new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											Intent intent_call_bx = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + car.getBxdh()));
											startActivity(intent_call_bx);
										}
									})
									.setNegativeButton("取消", null)
									.create().show();
								}
							}
						});
						
						xbdh.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								if(!car.getXbdh().equals("暂无")) {
									new AlertDialog.Builder(InsuranceActivity.this)
									.setMessage("是否拨打电话: " + car.getXbdh())
									.setPositiveButton("确认", new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											Intent intent_call_xb = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + car.getXbdh()));
											startActivity(intent_call_xb);
										}
									})
									.setNegativeButton("取消", null)
									.create().show();
									
								}
							}
						});
						int dp_height = 40;
						if(screenWidth == 480) {
							dp_height = 40;
						} else if(screenWidth == 720 || screenWidth == 800) {
							dp_height = 48;
						} else if(screenWidth == 540) {
							dp_height = 46;
						}
						LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, DimensUtil.dipTopx(InsuranceActivity.this, dp_height));
						lp.bottomMargin = 0;
						
						rl_xzqc.setBackgroundResource(R.drawable.setting_item_top_corner);
						rl_xzqc.setLayoutParams(lp);
						
						row_2.setVisibility(View.VISIBLE);
						cximg.setVisibility(View.VISIBLE);
						cxname.setVisibility(View.VISIBLE);
						cxad.setVisibility(View.VISIBLE);
						bxdh.setVisibility(View.VISIBLE);
						xbdh.setVisibility(View.VISIBLE);
						bd.setVisibility(View.GONE);
						break;
					}
				}
				
				
				liner_cx.addView(cx);
				
			}
		}
		
	}
	
	Handler mHandler_car = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			finishProgress();
			if(msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				VehicleInfoList vehicleInfoList = new VehicleInfoList(json);
				vehicleInfo = vehicleInfoList.getVehicleInfoList();
				application.setList_vehicleInfo(vehicleInfo);
				addInView();
			} else {
				showToast("加载数据失败");
			}
			super.handleMessage(msg);
		}
		
	};
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.carinsurances);
		showProgress("正在加载数据...");
		factory = getLayoutInflater();
		initView();
		application = (ProApplication) getApplication();
		
		DataLoader loader = new DataLoader(this);
		String url = MainConstants.HOST_test + HttpConfigAPI.findInsurance;
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		NameValuePair params = new BasicNameValuePair("userId", SharePrefenceUtil.getUserID(InsuranceActivity.this) + "");
		list.add(params);
		loader.DisplayData(url, list, mHandler, "", false);
		
	}
	
	private void initView() {
		liner_cx = (LinearLayout) findViewById(R.id.liner_cx);
		
		insurance_top = (RelativeLayout) findViewById(R.id.insurance_top);
		TextView title = (TextView) insurance_top.findViewById(R.id.top_middle);
		title.setText("我的车险");
		
		LinearLayout home_chose_City = (LinearLayout) insurance_top.findViewById(R.id.home_chose_City);
		home_chose_City.setVisibility(View.GONE);
		
		//TODO  车牌
		
	}
	

	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		super.onPause();
	}

	@Override
	protected void onResume() {
		MobclickAgent.onResume(this);
		super.onResume();
	}

	public void exit(View view) {
		for(int i = 0; i < liner_cx.getChildCount(); i++) {
			TextView tv_cx_id = (TextView) liner_cx.getChildAt(i).findViewById(R.id.bxID);
			if(vehicleInfo.size() > i) {
				VehicleInfo vi = vehicleInfo.get(i);
				String cx_id = tv_cx_id.getText().toString();
				if(!cx_id.equals("")) {
					if(!cx_id.equals(vi.getInsuranceCompanyId())) {
						TiJiao t = new TiJiao();
						t.insuranceCompanyId = cx_id;
						t.vehicleId = vi.getId();
						tijiao.add(t);
						
						DataLoader loader_jiao = new DataLoader(this);
						String url = MainConstants.HOST_test + HttpConfigAPI.UPDATE_VEHICLE;
						List<NameValuePair> list = new ArrayList<NameValuePair>();
						NameValuePair params = new BasicNameValuePair("vehicleInfo.userId", SharePrefenceUtil.getUserID(InsuranceActivity.this) + "");
						NameValuePair pa1 = new BasicNameValuePair("vehicleInfo.id",vi.getId());
						NameValuePair pa2 = new BasicNameValuePair("vehicleInfo.insuranceCompanyId", cx_id);
						list.add(params);
						list.add(pa1);
						list.add(pa2);
						loader_jiao.DisplayData(url, list, mHandler_vi, "", false);
					}
				}
			}
		}
		
		finish();
	}
	
	Handler mHandler_vi = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			String json = (String) msg.obj;
			try {
				if(!StringUtils.isSuccess(json)) {
					showToast("修改失败");
				} else {
					if(ProApplication.getInstance().getList_vehicleInfo() != null) {
						ProApplication.getInstance().getList_vehicleInfo().clear();
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}
		
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
	
	List<TiJiao> tijiao = new ArrayList<InsuranceActivity.TiJiao>();
	class TiJiao {
		private String vehicleId;
		private String insuranceCompanyId;
		private String insuranceCompany;
	}
	@Override
	public void onBackPressed() {
		exit(null);
		super.onBackPressed();
	}
	
	

}
